﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="Jim Liddell">
//   Copyright © Jim Liddell. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace TeamBuildBunnyConfiguration
{
    #region Usings

    using System;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Windows;

    using TeamBuildBunnyConfiguration.Models;
    using TeamBuildBunnyConfiguration.Views;

    #endregion

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region Methods

        private void OnStartup(object sender, StartupEventArgs e)
        {
            BuildBunnySettings settings = new BuildBunnySettings(new BuildBunnySettingsModel("TeamBuildBunnyWindowsService.exe.config"));
            settings.ShowDialog();
        }

        /// <summary>
        /// Restarts the Team Build Bunny service if it is running.
        /// </summary>
        private void OnExit(object sender, ExitEventArgs e)
        {
            ServiceController controller = new ServiceController("Team Build Bunny");

            // stop the service if it is running
            if (!controller.Status.Equals(ServiceControllerStatus.Stopped) &&
                !controller.Status.Equals(ServiceControllerStatus.StopPending))
            {
                controller.Stop();
                controller.WaitForStatus(ServiceControllerStatus.Stopped);
            }

            // start the service
            controller.Start();
        }

        #endregion

        private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            Trace.TraceError("An unhandled exception occured in Team Build Bunny Configuration. The Exception was '{0}'.", ex);
        }
    }
}